package cn.fetosoft.woodpecker.controller;

import cn.fetosoft.woodpecker.config.Constant;
import cn.fetosoft.woodpecker.core.data.entity.BaseElement;
import cn.fetosoft.woodpecker.core.data.form.ElementForm;
import cn.fetosoft.woodpecker.core.data.service.ElementService;
import cn.fetosoft.woodpecker.core.util.MenuTree;
import cn.fetosoft.woodpecker.struct.UserIdentity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author guobingbing
 * @wechat t_gbinb
 * @since 2021/7/3 17:08
 */
public abstract class BaseController {

	@Autowired
	private ElementService elementService;

    protected void setSessionUser(UserIdentity user, HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute(Constant.SESSION_USER, user);
    }

    protected UserIdentity getSessionUser(HttpServletRequest request){
        HttpSession session = request.getSession();
        return (UserIdentity) session.getAttribute(Constant.SESSION_USER);
    }

    protected void clearSessionUser(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.removeAttribute(Constant.SESSION_USER);
    }

	/**
	 * 创建树节点
	 * @param element
	 * @param before
	 * @param after
	 * @return
	 */
	protected MenuTree createChildNode(BaseElement element, BaseElement before, BaseElement after) {
		MenuTree tree = new MenuTree(element.getId(), element.getName(), element.getCategory());
		tree.setPlanId(element.getPlanId());
		tree.setParentId(element.getParentId());
		tree.setSort(element.getSort());
		tree.setUrl("/auth/element/gotoPage");
		tree.setEnabled(element.getEnabled()==null?true:element.getEnabled());
		if(!tree.isEnabled()) {
			tree.setText("<span style='color:#aaa'>" + element.getName() + "</span>");
		}
		if(before!=null){
			tree.setBefore(before.getId() + "," + before.getSort());
		}
		if(after!=null){
			tree.setAfter(after.getId() + "," + after.getSort());
		}
		return tree;
	}

	/**
	 * 递归生成树节点
	 * @param parent
	 * @throws Exception
	 */
	protected void recursionChildTree(MenuTree parent) throws Exception{
		ElementForm form = new ElementForm();
		form.setParentId(parent.getId());
		form.setAscField("sort");
		form.setRows(0);
		List<BaseElement> children = elementService.selectListByForm(form, BaseElement.class);
		if(!CollectionUtils.isEmpty(children)){
			for(int i=0; i<children.size(); i++){
				BaseElement child = children.get(i);
				BaseElement before = null, after = null;
				if(i>0){
					before = children.get(i-1);
				}
				if(i<(children.size()-1)){
					after = children.get(i+1);
				}
				MenuTree childTree = this.createChildNode(child, before, after);
				recursionChildTree(childTree);
				parent.addChild(childTree);
			}
		}
	}
}
